﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CS_NumberPlateReader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void readHistoryBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.readHistoryBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.cS_NPRDataSet);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: 이 코드는 데이터를 'cS_NPRDataSet.ReadHistory' 테이블에 로드합니다. 필요한 경우 이 코드를 이동하거나 제거할 수 있습니다.
            //this.readHistoryTableAdapter.InsertQuery("21노2216", "20131101", "092911");
            this.readHistoryTableAdapter.Fill(this.cS_NPRDataSet.ReadHistory);
        }

        private void txt_Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.readHistoryTableAdapter.FillBy(this.cS_NPRDataSet.ReadHistory, txt_Search.Text);
            }
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Playback_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = GRADataManager.GetSourceDataDirectory();
            dlg.Filter = "JPEG (*.jpg)|*.jpg";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                GRADataManager.SetSourceDataDirectory(Path.GetDirectoryName(dlg.FileName));
                if (Path.GetExtension(dlg.FileName).Equals(".jpg"))
                {
                    OpenNewImage(dlg.FileName);
                }
            }
        }

        private void DrawImage(Image img, GRAData gura)
        {
            Pen penRect = new Pen(new SolidBrush(Color.Red));

            // main
            Bitmap bm_main = new Bitmap(picMain.Width, picMain.Height);
            Graphics g_main = Graphics.FromImage(bm_main);

            g_main.DrawImage(img, new Point(0, 0));

            if (gura == null)
            {
                picMain.Image = bm_main;
                picPlate.Image = null;
                picText.Image = null;
                return;
            }

            g_main.DrawRectangle(penRect, gura.RectAreaList[0]);
            picMain.Image = bm_main;



            // Plate
            Bitmap bm_temp = new Bitmap(picMain.Width, picMain.Height);
            Graphics g_temp = Graphics.FromImage(bm_temp);
            g_temp.DrawImage(bm_main, new Point(0, 0));


            for (int i = 1; i < gura.RectAreaList.Count; i++)
            {
                g_temp.DrawRectangle(penRect, gura.RectAreaList[i]);
            }


            Rectangle rect_0 = GetPlateRect(gura.RectAreaList[0]);
            RectangleF rect_src = new RectangleF(rect_0.X, rect_0.Y, rect_0.Width, rect_0.Height);
            RectangleF rect_dest = new RectangleF((float)0, (float)0, (float)picPlate.Width, (float)picPlate.Height);
            Bitmap bm_plate = new Bitmap(picPlate.Width, picPlate.Height);
            Graphics g_plate = Graphics.FromImage(bm_plate);
            g_plate.DrawImage(bm_temp, rect_dest, rect_src, GraphicsUnit.Pixel);

            picPlate.Image = bm_plate;





            // Text
            Bitmap bm_Text = new Bitmap(picText.Width, picText.Height);
            Graphics g_Text = Graphics.FromImage(bm_Text);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;

            g_Text.DrawString(gura.PlateNumber, new Font("맑은 고딕", 26, FontStyle.Bold), new SolidBrush(Color.Black), new Point(picText.Width / 2, picText.Height / 2), sf);
            picText.Image = bm_Text;
        }

        private void OpenNewImage(string FileName)
        {
            GRAData gura = GRADataManager.GetPlateInfo_Image(System.IO.Path.GetFileNameWithoutExtension(FileName));
            DrawImage(Image.FromFile(FileName), gura);

            // 인식정보 저장
            this.readHistoryTableAdapter.InsertQuery(gura.PlateNumber, DateTime.Today.ToString("yyyyMMdd"), DateTime.Now.ToString("hhmmss"), imageToByteArray(Image.FromFile(FileName)));
            this.readHistoryTableAdapter.Fill(this.cS_NPRDataSet.ReadHistory);
        }

        private Rectangle GetPlateRect(Rectangle rectOriginal)
        {
            float plateRatio = (float)picPlate.Width / (float)picPlate.Height;
            float originRatio = (float)(rectOriginal.Width) / (float)(rectOriginal.Height);

            if (plateRatio == originRatio)
            {
                return rectOriginal;
            }
            else if (plateRatio < originRatio)
            {
                int yCenter = rectOriginal.Y + rectOriginal.Height / 2 + 2;
                int Height = Convert.ToInt32((rectOriginal.Width + 4) / plateRatio);
                int Y = yCenter - Height / 2;

                return new Rectangle(rectOriginal.X, Y, rectOriginal.Width + 4, Height);
            }
            else
            {
                int xCenter = rectOriginal.X + rectOriginal.Width / 2 + 2;
                int Width = Convert.ToInt32(plateRatio * (rectOriginal.Height + 4));
                int X = xCenter - Width / 2;

                return new Rectangle(X, rectOriginal.Y, Width, rectOriginal.Height + 4);
            }
        }

        private byte[] imageToByteArray(Image image)
        {
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        private Image byteArrayToImage(byte[] byteData)
        {
            MemoryStream ms = new MemoryStream(byteData);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private void readHistoryDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.RowIndex < readHistoryDataGridView.RowCount)
            {
                DataGridViewRow row = readHistoryDataGridView.Rows[e.RowIndex];
                DataRow dr = ((System.Data.DataRowView)(row.DataBoundItem)).Row;

                string licenseNumber = dr["LicenseNumber"].ToString();
                string filename = "";
                string sourceDataFolder = GRADataManager.GetSourceDataDirectory();
                string[] files = Directory.GetFiles(sourceDataFolder);
                foreach (string file in files)
                {
                    if (file.Contains(licenseNumber))
                    {
                        filename = file;
                        break;
                    }
                }


                Image CaptureImage = byteArrayToImage(dr["CaptureImage"] as byte[]);


                GRAData gura = GRADataManager.GetPlateInfo_Image(System.IO.Path.GetFileNameWithoutExtension(filename));
                DrawImage(CaptureImage, gura);

            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            if (readHistoryDataGridView.CurrentRow == null)
            {
                return;
            }

            DataGridViewRow row = readHistoryDataGridView.CurrentRow;
            DataRow dr = ((System.Data.DataRowView)(row.DataBoundItem)).Row;

            string licenseNumber = dr["LicenseNumber"].ToString();
            string filename = "";
            string sourceDataFolder = GRADataManager.GetSourceDataDirectory();
            string[] files = Directory.GetFiles(sourceDataFolder);
            foreach (string file in files)
            {
                if (file.Contains(licenseNumber))
                {
                    filename = file;
                    break;
                }
            }


            Image CaptureImage = byteArrayToImage(dr["CaptureImage"] as byte[]);
            GRAData gura = GRADataManager.GetPlateInfo_Image(System.IO.Path.GetFileNameWithoutExtension(filename));

            DrawImage(CaptureImage, gura);
        }
   }
}
